package com.chenken;

/**
 * 动态数组
 * @author ken.chen
 * @param <E>
 */
public class ArrayList<E> implements List<E>{

	private int size;
	
	private E[] elements;
	
	private static final int DEFAULT_CAPATICY = 5;
	
	public ArrayList(int capaticy) {
		capaticy = (capaticy<DEFAULT_CAPATICY)?DEFAULT_CAPATICY:capaticy;
		elements = (E[]) new Object[capaticy];
	}
	
	public ArrayList() {
		this(DEFAULT_CAPATICY);
	}
	
	@Override
	public int size() {
		return size;
	}

	@Override
	public boolean isEmpty() {
		return size == 0;
	}

	@Override
	public boolean contains(E element) {
		return indexOf(element)>-1;
	}

	@Override
	public E get(int index) {
		rangeCheck(index);
		return elements[index];
	}

	//replace  old
	@Override
	public E set(int index, E element) {
		rangeCheck(index);
		E oldElement = elements[index];
		elements[index] = element;
		return oldElement;
	}

	/**
	 * 总是往size的位置添加
	 */
	@Override
	public void add(E element) {
		add(size,element);
	}
	
	@Override
	public void add(int index, E element) {
		rangeCheckForAdd(index);
		ensureCapacity(size+1);
		for(int i = size-1;i>=index;i--) {
			elements[i+1] = elements[i];
		}
		elements[index] = element;
		size++;
	}
	
	/**
	 * 	保证容量
	 * 	每次扩容1.5倍
	 * @param capacity
	 */
	private void ensureCapacity(int capacity) {
		int oldCapacity = elements.length;
		if(oldCapacity >= capacity) {
			return;
		}
		int newCapacity = oldCapacity + (oldCapacity>>1);
		E[] newElements = (E[]) new Object[newCapacity];
		for(int i = 0;i<elements.length;i++) {
			newElements[i] = elements[i];
		}
		elements = newElements;
	}

	/**
	 * 挪动的范围是index+1到size-1
	 */
	@Override
	public E remove(int index) {
		rangeCheck(index);
		E element = elements[index];
		for(int i = index+1;i<size;i++) {
			elements[i-1] = elements[i];
		}
		elements[--size] = null;
		return element;
	}

	@Override
	public int indexOf(E element) {
		for(int i = 0;i<size;i++) {
			if(element.equals(elements[i])) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public void clear() {
		for(int i = 0;i<elements.length;i++) {
			elements[i] = null;
		}
		size = 0;
	}
	
	private void outOfBounds(int index) {
		throw new IndexOutOfBoundsException("Index:"+index+",Size:"+size);
	}
	
	private void rangeCheck(int index) {
		if(index < 0 || index >= size) {
			outOfBounds(index);
		}
	}
	
	private void rangeCheckForAdd(int index) {
		if(index < 0 || index > size) {
			outOfBounds(index);
		}
	}

	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("ArrayList {size=").append(size).append(",elements=[");
		for(int i = 0;i<size;i++) {
			if(i != 0) {
				stringBuilder.append(",");
			}
			stringBuilder.append(elements[i]);
		}
		stringBuilder.append("]}");
		return stringBuilder.toString();
	}
}
